<template>
  <div id="Monitoring">
    <ReturnPage class="mb10" />
    <!-- 操作按钮 -->
    <el-button
      type="primary"
      class="ml10"
      size="mini"
      @click="dialogVisible = true"
      >新增</el-button
    >
    <el-button
      type="primary"
      class="ml10"
      size="mini"
      :disabled="!multipleSelection.length"
      @click="changeStatus(0)"
      >启用</el-button
    >
    <el-button
      type="info"
      class="ml10"
      size="mini"
      :disabled="!multipleSelection.length"
      @click="changeStatus(1)"
      >禁用</el-button
    >
    <el-button
      type="danger"
      class="ml10"
      size="mini"
      :disabled="!multipleSelection.length"
      @click="delMonitor"
      >删除</el-button
    >
    <!-- 列表数据 -->
    <div class="tp_box mt10">
      <el-table
        :data="tableData"
        height="calc(100vh - 260px)"
        @selection-change="handleSelectionChange"
        size="mini"
        >>
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column
          prop="name"
          label="名称"
          align="center"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="trigger"
          label="触发器"
          align="center"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="key_"
          label="键值"
          align="center"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="delay"
          label="间隔"
          align="center"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="history"
          label="历史记录"
          align="center"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="type"
          label="类型"
          align="center"
          show-overflow-tooltip
        >
          <template slot-scope="scope">{{ scope.row.type | getType }}</template>
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          align="center"
          show-overflow-tooltip
        >
          <template slot-scope="scope"
            ><el-tag
              size="mini"
              :type="scope.row.status ? 'danger' : 'success'"
              >{{ scope.row.status ? "禁用" : "启用" }}</el-tag
            ></template
          >
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="pageNum"
        :limit.sync="pageSize"
        @pagination="getTableData()"
      />
    </div>
    <!-- 新增弹窗 -->
    <el-dialog
      title="新增监控项"
      :visible.sync="dialogVisible"
      width="40%"
      @close="closeDialog('form')"
    >
      <div class="form_box">
        <el-form
          :rules="rules"
          label-width="140px"
          ref="form"
          :model="form"
          size="mini"
        >
          <el-form-item label="名称" prop="name">
            <el-input
              v-model="form.name"
              placeholder="请输入监控项名称"
              style="width: 200px"
            ></el-input>
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-select
              v-model="form.type"
              placeholder="请选择类型"
              @change="typeChange"
            >
              <el-option
                :value="0"
                label="Zabbix 客户端"
                v-if="$route.query.type == 1"
              ></el-option>
              <el-option
                :value="13"
                label="SSH 客户端"
                v-if="$route.query.type == 2"
              ></el-option>
              <el-option
                :value="17"
                label="SNMP trap"
                v-if="$route.query.type == 2"
              ></el-option>
              <el-option
                :value="20"
                label="SNMP agent"
                v-if="$route.query.type == 2"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="键值" prop="key_">
            <el-input
              v-model="form.key_"
              placeholder="请输入键值"
              style="width: 200px"
            ></el-input>
            <el-button
              size="mini"
              class="ml10"
              @click="dialogVisible_key = true"
              :disabled="disableChoose"
              >选 择</el-button
            >
            <!--  <div
              :class="
                chooseKeyword_box
                  ? 'showChooseKeyword_box'
                  : 'closeChooseKeyword_box'
              "
            ></div> -->
          </el-form-item>
          <el-form-item label="主机接口">
            <el-input v-model="ip" disabled style="width: 200px"></el-input>
          </el-form-item>
          <!-- 选择snmp agent -->
          <el-form-item label="SNMP OID" prop="snmp_oid" v-if="form.type == 20">
            <el-input
              v-model="form.snmp_oid"
              style="width: 200px"
              placeholder="请输入SNMP OID"
            ></el-input>
          </el-form-item>

          <!-- 选择zabbix客户端 和 snmp agent 出现 -->
          <el-form-item label="更新间隔" prop="delay">
            <el-select v-model="form.delay" placeholder="请选择更新间隔">
              <el-option value="30s" label="30s"></el-option>
              <el-option value="1m" label="1m"></el-option>
              <el-option value="2h" label="2h"></el-option>
              <el-option value="1d" label="1d"></el-option>
            </el-select>
          </el-form-item>

          <!-- 选择ssh 客户端出现 -->
          <el-form-item label="用户名称" prop="username" v-if="form.type == 13">
            <el-input
              v-model="form.username"
              style="width: 200px"
              placeholder="请输入用户名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password" v-if="form.type == 13">
            <el-input
              v-model="form.password"
              style="width: 200px"
              placeholder="请输入密码"
              type="password"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="已执行的脚本"
            prop="params"
            v-if="form.type == 13"
          >
            <el-input type="textarea" v-model="form.params"></el-input>
          </el-form-item>

          <!-- 保留 -->
          <el-form-item label="历史数据保留时长" prop="history">
            <el-radio-group v-model="history_radio" size="mini">
              <el-radio-button label="1">不保留历史数据</el-radio-button>
              <el-radio-button label="2">存储</el-radio-button>
            </el-radio-group>
            <el-input
              v-if="history_radio == 2"
              class="ml10"
              v-model="form.history"
              style="width: 100px"
              placeholder="保留天数"
            ></el-input>
            <span v-if="history_radio == 2">&nbsp;&nbsp;天</span>
          </el-form-item>
          <el-form-item label="趋势存储时间" prop="trends">
            <el-radio-group v-model="trend_radio" size="mini">
              <el-radio-button label="1">不保留趋势数据</el-radio-button>
              <el-radio-button label="2">存储</el-radio-button>
            </el-radio-group>
            <el-input
              v-if="trend_radio == 2"
              class="ml10"
              v-model="form.trends"
              style="width: 100px"
              placeholder="保留天数"
            ></el-input>
            <span v-if="trend_radio == 2">&nbsp;&nbsp;天</span>
          </el-form-item>
          <!-- 选择snmp trap客户端 和 snmp agent客户端 出现 -->
          <el-form-item label="描述" prop="description" v-if="form.type != 0">
            <el-input type="textarea" v-model="form.description"></el-input>
          </el-form-item>
          <!-- 启用 -->
          <el-form-item label="已启用" prop="status">
            <el-checkbox v-model="form.status"></el-checkbox>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('form')" size="mini"
          >添 加</el-button
        >
        <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 选择键值的弹窗 -->
    <el-dialog
      title="标准检测器"
      :visible.sync="dialogVisible_key"
      width="50%"
      :before-close="handleClose"
    >
      <!--  -->
      <el-select
        v-model="typeKey_id"
        placeholder="请选择"
        class="mb10"
        @change="changeKeyType"
      >
        <el-option
          v-for="item in typeKey_"
          :key="item.zbTypeId"
          :value="item.zbTypeId"
          :label="item.zbTypeName"
        ></el-option>
      </el-select>
      <el-table
        :data="keyword_list"
        style="width: 100%"
        size="mini"
        :cell-style="cellStyle"
        @row-click="keywordClick_row"
        highlight-current-row="true"
      >
        <el-table-column prop="zbKey" label="键值" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="zbKeyName" label="名称" show-overflow-tooltip>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible_key = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getMonitor_Api, //监控项查询
  addMonitor_Api, //监控项添加
  updateMonitor_Api, //监控项编辑
  delMonitor_Api, //监控项删除
  getMonitorKey_List_Api, //查监控项键值类型数据
  getKey_byId_Api, //根据键值类型id查询键值
} from "@/api/automated/host.js";
import Template from "../ConfigurationManagement/model/Template.vue";
export default {
  components: { Template },
  data() {
    return {
      ip: null, //显示的主机接口
      //列表数据
      tableData: [],
      //分页
      query: {
        output: "extend",
        hostids: null,
        search: {
          // key_: "",
        },
        filter: {
          // type: "",
        },
      },
      //多选
      multipleSelection: [],
      //控制新增弹窗显示隐藏
      dialogVisible: false,
      //控制选择键值弹窗显示隐藏
      dialogVisible_key: false,
      //选择的键值类型
      typeKey_id: null,
      //监控项表单
      form: {
        name: null, //名称
        type: 0, //类型
        key_: null, //键值
        hostid: null, //主机接口
        history: 0, //历史数据保留时长
        trends: 0, //趋势存储时间
        status: true, //已启用
        //zabbix客户端 和 snmp agent
        delay: null, //更新间隔
        //snmp trap 和 snmp agent
        description: null, //描述
        //snmp agent
        snmp_oid: null, //snmpoid
        interfaceid: null, //主机接口id
        //ssh 客户端
        username: null, //用户名称
        password: null, //密码
        params: null, //已执行的脚本
      },
      //验证规则
      rules: {
        //名称
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        //键值
        key_: [{ required: true, message: "请输入键值", trigger: "change" }],
        //更新间隔
        delay: [
          { required: true, message: "请选择更新间隔", trigger: "change" },
        ],
        //snmpoid
        snmp_oid: [
          { required: true, message: "请输入SNMP OID", trigger: "blur" },
        ],
        history: [
          { required: true, message: "请输入保留天数", trigger: "blur" },
        ],
        trends: [
          { required: true, message: "请输入保留天数", trigger: "blur" },
        ],
        //ssh的用户名称
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
        ],
        params: [
          { required: true, message: "请输入已执行的脚本", trigger: "blur" },
        ],
      },
      history_radio: "1", //历史数据保留时长
      trend_radio: "1", //历史数据保留时长
      //渲染键值列表的数据
      keywordTable_data: [],
      //zabbix 客户端的键值
      keyword_list: [],
      //控制键值选择盒子显示隐藏
      // chooseKeyword_box: false,
      //分页
      pageSize: 20,
      pageNum: 1,
      total: 0,
      allData: [], //所有数据
    };
  },
  methods: {
    //获取列表数据
    getList() {
      getMonitor_Api(this.query).then((res) => {
        this.allData = res.data;
        this.total = res.data.length;
        this.getTableData();
      });
    },
    //分页获取数据
    getTableData() {
      this.tableData = this.allData.slice(
        (this.pageNum - 1) * this.pageSize,
        this.pageNum * this.pageSize
      );
    },
    //多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //关闭弹窗
    closeDialog(formName) {
      this.$refs[formName].resetFields();
    },
    //提交
    submitForm(formName) {
      //删除不需要的参数
      const tempObj = this.deleteObjectItem(this.form);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          tempObj.status ? (tempObj.status = 0) : (tempObj.status = 1);
          tempObj.history = tempObj.history + "d";
          tempObj.trends = tempObj.trends + "d";
          tempObj.value_type = 1;
          addMonitor_Api(tempObj).then((res) => {
            this.$message.success(res.msg);
            this.dialogVisible = false;
            this.getList();
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //键值列表的样式
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        return "color:#409eff;;cursor:pointer;";
      } else {
        return "";
      }
    },
    //点击键值列表
    keywordClick_row(row) {
      this.form.key_ = row.zbKey;
      this.dialogVisible_key = false;
    },
    /**
     * 使用test方法实现模糊查询
     * @param  {Array}  list     原数组
     * @param  {String} keyWord  查询的关键词
     * @return {Array}           查询的结果
     */
    /* fuzzyQuery(list, key_) {
      if (key_ == "") {
        this.chooseKeyword_box = false;
        this.keywordTable_data = this.zabbix_keyword;
        return;
      }
      var reg = new RegExp(key_);
      var arr = [];
      for (var i = 0; i < list.length; i++) {
        if (reg.test(list[i].key_)) {
          arr.push(list[i]);
        } else if (reg.test(list[i].name)) {
          arr.push(list[i]);
        }
      }
      if (!arr.length) {
        this.keywordTable_data = this.zabbix_keyword;
        this.chooseKeyword_box = false;
        return;
      } else {
        this.keywordTable_data = arr;
        this.chooseKeyword_box = true;
      }
      // return arr;
    }, */
    //删除监控项
    delMonitor() {
      const itemIds = this.multipleSelection.map((item) => item.itemid);
      delMonitor_Api(itemIds.join(",")).then((res) => {
        this.$message.success(res.msg);
        this.getList();
      });
    },
    //修改监控项状态
    changeStatus(state) {
      //获取id数组
      const itemIds = this.multipleSelection.map((item) => item.itemid);
      const tempArr = itemIds.map((item) => {
        return updateMonitor_Api({ status: state, itemid: item });
      });
      //获取结果
      Promise.all(tempArr).then((res) => {
        this.$message.success("操作成功");
        this.getList();
      });
    },
    //提交表单之前，删除不需要的项
    deleteObjectItem({ ...object }) {
      if (object.type == 0) {
        //检查类型为zabbix ，删除snmp trap 和 snmp agent 和 ssh
        delete object.description;
        delete object.snmp_oid;
        delete object.username;
        delete object.password;
        delete object.params;
      } else if (object.type == 17) {
        //检查类型为snmp trap 删除 zabbix 和 snmp agent 和 ssh
        delete object.snmp_oid;
        delete object.username;
        delete object.password;
        delete object.params;
      } else if (object.type == 13) {
        //类型为ssh 客户端 删除 zabbix 和 snmp agent 和 snmp trap
        delete object.snmp_oid;
      } else {
        //检查类型为snmp agent ， 删除zabbix和snmp trap 和 ssh
        delete object.username;
        delete object.password;
        delete object.params;
      }
      return object;
    },
    //获取键值类型列表
    getMonitorKey_Menu() {
      getMonitorKey_List_Api().then((res) => {
        this.typeKey_ = res;
      });
    },
    //类型切换
    typeChange(val) {
      if (val == 0) {
        this.typeKey_id = 1;
        this.disableChoose = false;
        //根据id获取数据
        getKey_byId_Api({ zbTypeId: this.typeKey_id }).then((res) => {
          this.keyword_list = res;
        });
      } else if (val == 17) {
        this.typeKey_id = 6;
        this.disableChoose = false;
        getKey_byId_Api({ zbTypeId: this.typeKey_id }).then((res) => {
          this.keyword_list = res;
        });
      } else if (val == 20) {
        this.disableChoose = true;
      } else if (val == 13) {
        this.disableChoose = true;
      }
    },
    //切换键值类型的值
    changeKeyType(id) {
      this.typeKey_id = id;
      getKey_byId_Api({ zbTypeId: this.typeKey_id }).then((res) => {
        this.keyword_list = res;
      });
    },
    //没有切换类型时拿键值列表
    getKeyOnce() {
      this.typeKey_id = this.$route.query.type == 1 ? 1 : 6;
      getKey_byId_Api({ zbTypeId: this.typeKey_id }).then((res) => {
        this.keyword_list = res;
      });
    },
  },
  created() {
    //设置类型
    this.form.type = this.$route.query.type == 1 ? 0 : 17;
    //获取主机id 和 interfaceid
    this.query.hostids = this.$route.query.hostid;
    this.form.hostid = this.$route.query.hostid;
    this.form.interfaceid = this.$route.query.interfaceid;
    this.ip = this.$route.query.ip;
    // this.keywordTable_data = this.zabbix_keyword;
    //获取数据
    this.getList();
    //获取键值类型列表
    this.getMonitorKey_Menu();
    this.getKeyOnce(); //第一次没有切换类型时拿键值列表
  },
  watch: {
    history_radio: {
      handler(newVal, oldVal) {
        if (newVal == 1) {
          this.form.history = 0;
        } else {
          this.form.history = null;
        }
      },
    },
    trend_radio: {
      handler(newVal, oldVal) {
        if (newVal == 1) {
          this.form.trends = 0;
        } else {
          this.form.trends = null;
        }
      },
    },
    //监听添加弹窗，控制两个保留时长按钮
    dialogVisible: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.history_radio = 1;
          this.trend_radio = 1;
        }
      },
    },
  },
  filters: {
    //过滤类型
    getType(val) {
      switch (val) {
        case 0:
          return "Zabbix 客户端";
        case 2:
          return "zabbix 采集器";
        case 3:
          return "简单检查";
        case 5:
          return "内部检查";
        case 7:
          return "zabbix agent（主动）";
        case 9:
          return "web监控项";
        case 10:
          return "外部检查";
        case 11:
          return "数据库监控";
        case 12:
          return "IPMI agent";
        case 13:
          return "SSH agent";
        case 14:
          return "Telnet agent";
        case 15:
          return "可计算的监控";
        case 16:
          return "JMX agent";
        case 17:
          return "SNMP trap";
        case 18:
          return "相关项监控";
        case 19:
          return "HTTP agent";
        case 20:
          return "SNMP agent";
        case 21:
          return "脚本";
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.showChooseKeyword_box {
  position: absolute;
  display: block;
  // width: 500px;
  // height: 200px;
  left: 210px;
  top: 35px;
  background-color: #ffffff;
  border-radius: 5px;
  box-shadow: 0px 0px 5px 1px #e2e0e0;
  z-index: 999;
  animation: showChooseKeyword_box 0.3s forwards;
}
.closeChooseKeyword_box {
  display: none;
}
@keyframes showChooseKeyword_box {
  from {
    width: 0px;
    height: 0px;
    overflow: hidden;
  }
  to {
    width: 600px;
    max-height: 400px;
    padding: 10px;
    overflow-y: scroll;
  }
}
</style>